package com.ruoyi.web.controller.course;

import java.io.File;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.doudou.ffmpeg.video.FFmpegUtil;
import com.doudou.minio.Minio;
import com.ruoyi.course.domain.CourseWareComment;
import com.ruoyi.ex.domain.ExQuestion;
import com.ruoyi.ex.service.IExQuestionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.course.domain.CourseWare;
import com.ruoyi.course.service.ICourseWareService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;


/**
 * 培训课件Controller
 *
 * @author zzx
 * @date 2023-03-29
 */
@Api("培训课件")
@RestController
@RequestMapping("/course/course_ware")
public class CourseWareController extends BaseController {
    @Autowired private ICourseWareService courseWareService;
    @Autowired private IExQuestionService exQuestionService;
    @Autowired private Minio minio;

    @Value("${postpartum.profile}")
    private String profilePath;

    /**
     * 查询培训课件列表
     */

    @GetMapping("/list")
    @ApiOperation("查询培训课件列表")
    public TableDataInfo list(CourseWare courseWare) {
        startPage();
        courseWare.setDeptId(getDeptId());
        courseWare.setUserId(getUserId());
        List<CourseWare> list = courseWareService.selectCourseWareList(courseWare);
        return getDataTable(list);
    }

    /**
     * 导出培训课件列表
     */
    @PreAuthorize("@ss.hasPermi('course:course_ware:export')")
    @Log(title = "培训课件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CourseWare courseWare) {
        courseWare.setDeptId(getDeptId());
        courseWare.setUserId(getUserId());
        List<CourseWare> list = courseWareService.selectCourseWareList(courseWare);
        ExcelUtil<CourseWare> util = new ExcelUtil<CourseWare>(CourseWare.class);
        util.exportExcel(response, list, "培训课件数据");
    }

    /**
     * 获取培训课件详细信息
     */

    @GetMapping(value = "/{id}")
    @ApiOperation("获取培训课件详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(courseWareService.selectCourseWareById(id));
    }

    /**
     * 新增培训课件
     */
    @PreAuthorize("@ss.hasPermi('course:course_ware:add')")
    @Log(title = "培训课件", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增培训课件")
    public AjaxResult add(@RequestBody CourseWare courseWare) {
        courseWare.setDeptId(getDeptId());
        courseWare.setUserId(getUserId());
        courseWare.setStatus(0);
        return toAjax(courseWareService.insertCourseWare(courseWare));
    }

    /**
     * 上传课件
     */
    @PreAuthorize("@ss.hasPermi('course:course_ware:add')")
    @Log(title = "上传课件", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    @ApiOperation("新增培训课件")
    public AjaxResult add(MultipartFile file){
        //临时文件位置
        String newPath = profilePath + "wareTemporary/";
        String originalFilename = file.getOriginalFilename();
        UUID uuid = UUID.randomUUID();
        //临时视频地址
        String temporaryVideoPath = newPath + uuid + originalFilename.substring(originalFilename.lastIndexOf("."));
        // 将上传的文件保存到临时文件中
        File tempFile = FileUtil.file(temporaryVideoPath);
        //临时图片地址
        String temporaryThumbnailPath = newPath + uuid + ".png";
        File thumbnail = new File(temporaryThumbnailPath);
        try{
            file.transferTo(tempFile);
            //获取课件的时长和缩略图
            FFmpegUtil.Video tempPath = FFmpegUtil.getTempPath(thumbnail,tempFile);
            if (!tempPath.getGetThumbnail()){
                return AjaxResult.error("确认文件类型出错");
            }
            //上传缩略图
            String thumbnailUrl = minio.uploadFile(thumbnail);
            //上传视频
            String videoUrl = minio.uploadFile(tempFile);
            return AjaxResult.success(videoUrl).put("thumbnail",thumbnailUrl).put("duration",tempPath.getDuration());
        }catch (Exception e){
            logger.error("上传文件失败",e);
            return AjaxResult.error(e.getMessage());
        }finally {
            //删除临时文件
            thumbnail.delete();
            tempFile.delete();
        }
    }


    /**
     * 新增培训课件的题目
     */
    @PreAuthorize("@ss.hasPermi('course:course_ware:add')")
    @Log(title = "培训课件题目", businessType = BusinessType.INSERT)
    @PostMapping("/question/{wareId}")
    @ApiOperation("新增培训课件的题目")
    public AjaxResult addWareQuestion(@PathVariable("wareId")Long wareId, @RequestBody ExQuestion question) {
        question.setDeptId(getDeptId());
        //添加题目
        exQuestionService.insertExQuestion(question);
        //添加中间表
        return toAjax(courseWareService.insertWareQuestion(wareId,question.getId()));
    }

    /**
     * 发表评论
     */

    @Log(title = "培训课件题目评论", businessType = BusinessType.INSERT)
    @PostMapping("/comment")
    @ApiOperation("发表评论")
    public AjaxResult addWareComment(@RequestBody CourseWareComment courseWareComment) {
        courseWareComment.setUserId(getUserId());
        //添加评论
        return toAjax(courseWareService.insertWareComment(courseWareComment));
    }

    /**
     * 修改培训课件
     */
    @PreAuthorize("@ss.hasPermi('course:course_ware:edit')")
    @Log(title = "培训课件", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改培训课件")
    public AjaxResult edit(@RequestBody CourseWare courseWare) {
        return toAjax(courseWareService.updateCourseWare(courseWare));
    }

    /**
     * 删除培训课件
     */
    @PreAuthorize("@ss.hasPermi('course:course_ware:remove')")
    @Log(title = "培训课件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除培训课件")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(courseWareService.deleteCourseWareByIds(ids));
    }

    /**
     * 删除培训课件题目
     */
    @PreAuthorize("@ss.hasPermi('course:course_ware:remove')")
    @Log(title = "培训课件题目", businessType = BusinessType.DELETE)
    @DeleteMapping("/question/{wareId}/{questionId}")
    @ApiOperation("删除培训课件题目")
    public AjaxResult removeQuestion(@PathVariable("wareId") Long wareId,@PathVariable("questionId")Long questionId) {
        //删除题目
        exQuestionService.deleteExQuestionById(questionId);
        //删除中间表
        return toAjax(courseWareService.deleteCourseWareQuestion(wareId,questionId));
    }

    /**
     * 删除评论
     */

    @Log(title = "培训课件题目评论", businessType = BusinessType.DELETE)
    @DeleteMapping("/comment/{id}")
    @ApiOperation("删除评论")
    public AjaxResult removeComment(@PathVariable("id") Long id) {
        //删除评论
        return toAjax(courseWareService.deleteCourseWareComment(id));
    }


    /**
     * 课件观看次数加一
     */
    @Log(title = "课件观看次数加一", businessType = BusinessType.UPDATE)
    @PutMapping("/watch-count-add/{wareId}")
    @ApiOperation("课件观看次数加一")
    public AjaxResult watchCountAdd(@PathVariable("wareId")Long wareId) {
        return toAjax(courseWareService.updateWatchCountAdd(wareId));
    }
}
